<template>
  <div class="order">
    <div v-if="!roleOperation">
      <div style="display: flex; justify-content: space-between">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="角色名称">
            <el-input v-model="formInline.roleName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchList">查询</el-button>
            <el-button type="default" @click="resetFormConditions">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="addRole" class="addBtn">新增</el-button>
      </div>
      <div class="tables">
        <el-table ref="multipleTable" :data="tables" tooltip-effect="dark" style="width: 100%">
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="name" label="角色名称"></el-table-column>
          <el-table-column label="角色属性" pro>
            <template slot-scope="scope" v-if='scope.row.type!=8'>
              <span>{{scope.row.typeName}}</span>
            </template>
            <template slot-scope="scope" v-if='scope.row.type==8'>
              <span>司机</span>
            </template>
          </el-table-column>
          <el-table-column prop="createName" label="创建人"></el-table-column>
          <el-table-column label="创建时间">
            <template slot-scope="scope">{{scope.row.updateAt}}</template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <el-button @click="handleViewRole(scope.row,1)" type="text" size="small">查看</el-button>
              <el-button @click="handleEdit(scope.row,2)" type="text" size="small">编辑</el-button>
              <el-button type="text" size="small" @click="deleteRole(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <div v-if="roleOperation">
      <el-button type="private" size="small" @click="goBack">返回</el-button>
      <div class="addForm" v-if="!isUpdate">
        <div style="width:50%;">
          <el-tree :data="data2" show-checkbox node-key="id" ref="tree2" :default-checked-keys="defaultChecked" :props="defaultProps" @check-change="getNodes"></el-tree>
        </div>
        <div style="width:50%">
          <el-form ref="detailForm" :model="detailForm" :rules="rules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="detailForm.roleName" class="roleName"></el-input>
            </el-form-item>
            <!-- <companyTypeInput @selectChange="getVal" /> -->
            <el-form-item label='角色属性' prop='roleType'>
              <el-select v-model='detailForm.roleType'>
                <el-option v-for='item in compnayTypeList' :label='item.name' :value='item.id' :key='item.id'></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('detailForm')" v-if="!showBtns">确定</el-button>
              <!-- <el-button type="primary" @click="editCurrentForm">编辑</el-button> -->
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="addForm" v-if="isUpdate">
        <div style="width:50%;">
          <el-tree :data="data2" show-checkbox node-key="id" ref="tree2" :default-checked-keys="defaultChecked" :props="defaultProps" @check-change="getNodes"></el-tree>
        </div>
        <div style="width:50%">
          <el-form ref="detailForm" :model="detailForm" :rules="rules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="detailForm.roleName" class="roleName"></el-input>
            </el-form-item>
            <companyTypeInput :code="test" @selectChange="getVal" />
            <el-form-item>
              <el-button type="primary" @click="submitForm('detailForm')">确定</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import companyTypeInput from "@/components/companyTypeInput/companyTypeInput";
export default {
  inject: ["reload"],
  data() {
    return {
      tables: [],
      data2: [],
      test: "123",
      defaultProps: {
        children: "children",
        label: "label"
      },
      formInline: {
        productionCompany: "",
        disposition: "",
        wasteType: "",
        status: "",
        userName: "",
        roleName: ""
      },
      detailForm: {
        companyType: "",
        roleName: "",
        remark: "",
        roleType: ''
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        companyType: [{
          required: true,
          message: "请选择单位类型",
          trigger: "change"
        }],
        roleType: [{
          required: true,
          message: '请选择角色属性',
          trigger: "change"
        }]
      },
      currentPage: 1,
      total: 10,
      page: 1,
      limit: 10,
      isAddRole: false,
      isAddView: false,
      isUpdate: false,
      roleOperation: false,
      showBtns: false,
      timer: null,
      addRoleMenuListId: [],
      defaultChecked: [],
      companyType: "",
      compnayTypeList: []
    };
  },
  mounted() {
    this.searchResult();
    sessionStorage.clear();
  },
  methods: {
    getVal(val) {
      this.detailForm.companyType = val;
    },
    searchResult() {
      this.$common
        .$ajax(
          "/sys/role/list", {
            limit: this.limit,
            page: this.page,
            roleName: this.formInline.roleName
          },
          "get"
        )
        .then(res => {
          this.tables = res.data.page.list;
          this.total = res.data.page.totalCount;
        });
    },
    searchList() {
      this.searchResult();
    },
    handleSizeChange(val) {
      this.limit = val;
      this.searchResult();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.searchResult();
    },
    resetFormConditions() {
      this.formInline.roleName = "";
      this.searchResult();
    },
    addRole() {
      this.roleOperation = true;
      //   新增
      this.showBtns = false;
      this.isUpdate = false;
      // 显示树形结构
      this.$common.$ajax("/sys/menu/list", {}, "get").then(res => {
        this.data2 = res.data.body;
      });
      this.initCompanyType()
    },
    initCompanyType() {
      this.$common.$ajax("/sys/company/type/list", {}, "get").then(res => {
        res.data.body.push({
          id: 8,
          name: '司机'
        })
        this.compnayTypeList = res.data.body
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleViewRole(row) {
      this.$common.$ajax("/sys/menu/list", {}, "get").then(res => {
        this.data2 = res.data.body;
      });
      console.log(row);
      this.roleOperation = true;
      this.showBtns = true;
      this.detailForm.roleName = row.name;
      this.detailForm.companyType = row.type;
      this.$nextTick(() => {
        console.log(row.menuIdList.slice(0, -1));
        this.$refs.tree2.setCheckedKeys(row.menuIdList.slice(0, -1), true);
      });
      sessionStorage.types = row.type;
      //   this.defaultChecked = row.menuIdList;
    },
    handleEdit(row, type) {
      this.$common.$ajax("/sys/menu/list", {}, "get").then(res => {
        this.data2 = res.data.body;
      });
      this.roleOperation = true;
      this.showBtns = true;
      this.detailForm.roleName = row.name;
      this.detailForm.companyType = row.type;
      this.$nextTick(() => {
        console.log(row.menuIdList.slice(0, -1));
        this.$refs.tree2.setCheckedKeys(row.menuIdList.slice(0, -1), true);
      });
      sessionStorage.types = row.type;
      this.isUpdate = true;
    },
    goBack() {
      this.reload();
    },
    editCurrentForm() {
      this.isUpdate = true;
    },
    deleteRole(row) {
      console.log(row);
      this.$common.$ajax("/sys/role/delete", [row.id], "post").then(res => {
        this.$message({
          message: "删除成功",
          type: "success",
          duration: 1000
        });
        this.reload();
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.isUpdate) {
            //    编辑
            this.$common
              .$ajax(
                "/sys/role/save", {
                  name: this.detailForm.roleName,
                  type: this.detailForm.companyType,
                  menuIdList: this.menuIdList
                },
                "post"
              )
              .then(res => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                  duration: 1000
                });
                this.reload();
              });
          } else {
            this.$common
              .$ajax(
                "/sys/role/save", {
                  name: this.detailForm.roleName,
                  type: this.detailForm.roleType,
                  menuIdList: this.menuIdList
                },
                "post"
              )
              .then(res => {
                this.$message({
                  message: "新增成功",
                  type: "success",
                  duration: 1000
                });
                this.reload();
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getNodes() {
      console.log(this.$refs.tree2.getCheckedKeys());
      console.log(this.$refs.tree2.getHalfCheckedKeys());
      //   获取选中的节点
      var nodesChecked = this.$refs.tree2.getCheckedKeys();
      // 获取半选的节点
      var halfChecked = this.$refs.tree2.getHalfCheckedKeys();
      console.log(nodesChecked.concat(halfChecked));
      this.menuIdList = nodesChecked.concat(halfChecked);
    }
  },
  components: {
    companyTypeInput
  }
};

</script>
<style lang="scss">
.tables {
  margin-top: 20px;
}

.addBtn {
  height: 40px !important;
}

.wrapper {
  display: flex;
  justify-content: space-between;

  .menuListTree {
    width: 50%;
  }

  .roleViews {
    width: 50%;
  }
}

.addForm {
  display: flex;
  justify-content: space-between;
  background: #fff;
  width: 50%;
}

</style>
